<template>
  <div class="document-category-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="breadcrumb">
          <el-button link @click="goBack">
            <el-icon><ArrowLeft /></el-icon> 返回文档管理
          </el-button>
        </div>
        <h1 class="page-title">{{ categoryTitle }}</h1>
        <p class="page-subtitle">{{ categoryDescription }}</p>
      </div>
      <div class="header-actions">
        <el-button size="large" type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon> 上传文档
        </el-button>
        <el-button size="large" @click="refreshDocuments">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和视图切换 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文档名称或描述"
          clearable
          @input="filterDocuments"
          style="width: 300px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-right">
        <el-radio-group v-model="viewMode" @change="filterDocuments">
          <el-radio-button value="grid">网格视图</el-radio-button>
          <el-radio-button value="list">列表视图</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 文档展示区域 -->
    <div class="main-content">
      <div class="panel-card">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="document-grid">
          <div
            v-for="doc in filteredDocuments"
            :key="doc.id"
            class="document-card"
            @click="handlePreviewDocument(doc)"
          >
            <div class="document-icon">
              <el-icon>
                <component :is="getFileIcon(doc.fileType)" />
              </el-icon>
            </div>
            <div class="document-info">
              <h3 class="document-title">{{ doc.name }}</h3>
              <p class="document-desc">{{ doc.description }}</p>
              <div class="document-meta">
                <span class="document-category">{{ getCategoryLabel(doc.category) }}</span>
                <span class="document-size">{{ doc.fileType === 'link' ? '链接' : formatFileSize(doc.fileSize) }}</span>
              </div>
              <div class="document-actions">
                <el-button size="small" type="primary" @click.stop="downloadDocument(doc)">
                  <el-icon><Download /></el-icon> 下载
                </el-button>
                <el-button size="small" @click.stop="copyLink(doc)">
                  <el-icon><Link /></el-icon> 复制链接
                </el-button>
                <el-button 
                  v-if="userRole === 'admin' || userRole === 'superadmin'" 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteDocument(doc)"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="document-list">
          <el-table :data="filteredDocuments" style="width: 100%">
            <el-table-column prop="name" label="文档名称" min-width="220">
              <template #default="{ row }">
                <div class="document-name-cell">
                  <el-icon style="margin-right: 8px; color: #409eff;">
                    <component :is="getFileIcon(row.fileType)" />
                  </el-icon>
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="220" />
            <el-table-column prop="category" label="分类" width="120">
              <template #default="{ row }">
                <el-tag v-if="getCategoryTagType(row.category)" :type="getCategoryTagType(row.category)" size="small">
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
                <el-tag v-else size="small">
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="fileSize" label="大小" width="120">
              <template #default="{ row }">
                {{ row.fileType === 'link' ? '链接' : formatFileSize(row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <div style="display: flex; gap: 8px; flex-wrap: nowrap;">
                  <el-button size="small" type="primary" @click="downloadDocument(row)">
                    <el-icon><Download /></el-icon> 下载
                  </el-button>
                  <el-button size="small" @click="copyLink(row)">
                    <el-icon><Link /></el-icon> 复制
                  </el-button>
                  <el-button 
                    v-if="userRole === 'admin' || userRole === 'superadmin'" 
                    size="small" 
                    type="danger" 
                    @click="deleteDocument(row)"
                  >
                    <el-icon><Delete /></el-icon> 删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredDocuments.length === 0" class="empty-state">
          <el-empty description="暂无文档" />
        </div>
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文档" width="500px">
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="文档名称" required>
          <el-input v-model="uploadForm.name" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档描述">
          <el-input v-model="uploadForm.description" type="textarea" placeholder="请输入文档描述" />
        </el-form-item>
        <el-form-item label="文档分类">
          <el-select v-model="uploadForm.category" placeholder="选择分类">
            <el-option :label="getCategoryLabel(category)" :value="category" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传方式">
          <el-radio-group v-model="uploadForm.uploadType">
            <el-radio value="file">本地文件</el-radio>
            <el-radio value="link">网盘链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="uploadForm.uploadType === 'file'" label="选择文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="false"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.gif"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
          <div v-if="uploadForm.file" class="selected-file">
            已选择: {{ uploadForm.file.name }}
          </div>
        </el-form-item>
        <el-form-item v-if="uploadForm.uploadType === 'link'" label="网盘链接">
          <el-input v-model="uploadForm.cloudLink" placeholder="请输入网盘链接" />
          <el-button @click="testCloudLink" style="margin-top: 8px;">测试链接</el-button>
        </el-form-item>
        <el-form-item v-if="showExtractCode" label="提取码">
          <el-input v-model="uploadForm.extractCode" placeholder="请输入提取码" />
          <el-button @click="validateExtractCode" style="margin-top: 8px;">验证提取码</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="uploadDocument">上传</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="文档预览" width="80%" :fullscreen="isMobile">
      <div v-if="previewDocument" class="preview-content">
        <div class="preview-header">
          <h3>{{ previewDocument.name }}</h3>
          <p>{{ previewDocument.description }}</p>
        </div>
        <div class="preview-body">
          <div v-if="previewDocument.fileType === 'link'" class="link-preview">
            <p>文档链接：{{ previewDocument.url }}</p>
            <el-button type="primary" @click="openLink(previewDocument.url)">打开链接</el-button>
          </div>
          <div v-else-if="isImageFile(previewDocument.fileType)" class="image-preview">
            <img :src="previewDocument.url" :alt="previewDocument.name" style="max-width: 100%;" />
          </div>
          <div v-else class="file-preview">
            <p>文件类型：{{ previewDocument.fileType.toUpperCase() }}</p>
            <p>文件大小：{{ formatFileSize(previewDocument.fileSize) }}</p>
            <el-button type="primary" @click="downloadDocument(previewDocument)">下载文件</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, Download, Delete, Search, Refresh, Link, 
  ArrowLeft, Document, Picture, Link as LinkIcon
} from '@element-plus/icons-vue'
import AV from '../leancloud'

const route = useRoute()
const router = useRouter()

// 响应式数据
const documents = ref([])
const searchKeyword = ref('')
const viewMode = ref('grid')
const showUploadDialog = ref(false)
const showPreviewDialog = ref(false)
const showExtractCode = ref(false)
const previewDocument = ref(null)
const uploadRef = ref(null)

// 上传表单
const uploadForm = ref({
  name: '',
  description: '',
  category: '',
  uploadType: 'file',
  file: null,
  cloudLink: '',
  extractCode: ''
})

// 用户角色
const userRole = ref(localStorage.getItem('userRole') || 'user')

// 计算属性
const category = computed(() => route.params.category)
const categoryTitle = computed(() => getCategoryLabel(category.value))
const categoryDescription = computed(() => getCategoryDescription(category.value))

const filteredDocuments = computed(() => {
  let filtered = documents.value.filter(doc => doc.category === category.value)
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(doc => 
      doc.name.toLowerCase().includes(keyword) || 
      doc.description.toLowerCase().includes(keyword)
    )
  }
  
  return filtered
})

// 分类描述
function getCategoryDescription(category) {
  const descriptions = {
    'form-template': '管理各种表单模板，包括检验报告、质量记录等',
    'national-standard': '国家标准文件，包括行业标准、技术规范等',
    'enterprise-standard': '企业内部标准文件，包括工艺标准、操作规程等',
    'regulatory-document': '规范性文件，包括管理制度、工作流程等',
    'technical-document': '技术文档，包括技术规范、设计文档等',
    'operation-manual': '操作手册，包括设备操作、工艺流程等',
    'third-party-report': '第三方检测报告、认证文件等',
    'other': '其他相关文档'
  }
  return descriptions[category] || '相关文档'
}

// 分类标签
function getCategoryLabel(category) {
  const labelMap = {
    'form-template': '表单模板',
    'national-standard': '国家标准',
    'enterprise-standard': '企业标准',
    'regulatory-document': '规范性文件',
    'technical-document': '技术文档',
    'operation-manual': '操作手册',
    'third-party-report': '三方报告',
    'other': '其他'
  }
  return labelMap[category] || '其他'
}

// 分类标签类型
function getCategoryTagType(category) {
  const typeMap = {
    'form-template': 'primary',
    'national-standard': 'success',
    'enterprise-standard': 'warning',
    'regulatory-document': 'info',
    'technical-document': 'danger',
    'operation-manual': 'warning',
    'third-party-report': 'success',
    'other': ''
  }
  return typeMap[category] || ''
}

// 获取文件图标
function getFileIcon(fileType) {
  const iconMap = {
    'pdf': 'Document',
    'doc': 'Document',
    'docx': 'Document',
    'xls': 'Document',
    'xlsx': 'Document',
    'ppt': 'Document',
    'pptx': 'Document',
    'txt': 'Document',
    'jpg': 'Picture',
    'jpeg': 'Picture',
    'png': 'Picture',
    'gif': 'Picture',
    'link': 'LinkIcon'
  }
  return iconMap[fileType] || 'Document'
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
function formatDate(date) {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 判断是否为图片文件
function isImageFile(fileType) {
  return ['jpg', 'jpeg', 'png', 'gif'].includes(fileType)
}

// 返回文档管理
function goBack() {
  router.push('/document-manage')
}

// 刷新文档
async function refreshDocuments() {
  await fetchDocuments()
  ElMessage.success('文档列表已刷新')
}

// 获取文档列表
async function fetchDocuments() {
  try {
    const query = new AV.Query('Document')
    query.equalTo('category', category.value)
    query.descending('uploadTime')
    const results = await query.find()
    
    documents.value = results.map(doc => ({
      id: doc.id,
      name: doc.get('name'),
      description: doc.get('description'),
      category: doc.get('category') || 'other', // 确保有默认值
      fileType: doc.get('fileType'),
      fileSize: doc.get('fileSize'),
      url: doc.get('url'),
      uploadTime: doc.get('uploadTime') || doc.createdAt
    }))
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  }
}

// 筛选文档
function filterDocuments() {
  // 通过计算属性自动筛选
}

// 打开上传对话框
function openUploadDialog() {
  uploadForm.value = {
    name: '',
    description: '',
    category: category.value, // 确保设置为当前分类
    uploadType: 'file',
    file: null,
    cloudLink: '',
    extractCode: ''
  }
  showUploadDialog.value = true
}

// 处理文件选择
function handleFileChange(file) {
  uploadForm.value.file = file.raw
}

// 检测是否为百度网盘链接
function isBaiduPanLink(url) {
  return url.includes('pan.baidu.com')
}

// 测试网盘链接
function testCloudLink() {
  if (!uploadForm.value.cloudLink) {
    ElMessage.warning('请先输入网盘链接')
    return
  }
  
  if (isBaiduPanLink(uploadForm.value.cloudLink)) {
    showExtractCode.value = true
    ElMessage.info('检测到百度网盘链接，请输入提取码')
  } else {
    showExtractCode.value = false
    ElMessage.success('链接格式正确')
  }
}

// 验证提取码
function validateExtractCode() {
  if (!uploadForm.value.extractCode) {
    ElMessage.warning('请输入提取码')
    return
  }
  
  if (uploadForm.value.extractCode.length < 4) {
    ElMessage.warning('提取码长度不正确')
    return
  }
  
  ElMessage.success('提取码格式正确')
}

// 上传文档
async function uploadDocument() {
  try {
    if (!uploadForm.value.name.trim()) {
      ElMessage.error('请输入文档名称')
      return
    }

    if (uploadForm.value.uploadType === 'file' && !uploadForm.value.file) {
      ElMessage.error('请选择要上传的文件')
      return
    }

    if (uploadForm.value.uploadType === 'link' && !uploadForm.value.cloudLink.trim()) {
      ElMessage.error('请输入网盘链接')
      return
    }

    ElMessage.info('正在上传文档...')

    const document = new AV.Object('Document')
    document.set('name', uploadForm.value.name)
    document.set('description', uploadForm.value.description)
    document.set('category', uploadForm.value.category)

    if (uploadForm.value.uploadType === 'file') {
      const file = uploadForm.value.file
      const avFile = new AV.File(file.name, file)
      await avFile.save()
      
      document.set('fileType', file.name.split('.').pop().toLowerCase())
      document.set('fileSize', file.size)
      document.set('url', avFile.url())
    } else {
      document.set('fileType', 'link')
      document.set('fileSize', 0)
      document.set('url', uploadForm.value.cloudLink)
      if (uploadForm.value.extractCode) {
        document.set('extractCode', uploadForm.value.extractCode)
      }
    }

    document.set('uploadTime', new Date())
    await document.save()

    ElMessage.success('文档上传成功')
    showUploadDialog.value = false
    await fetchDocuments()
  } catch (error) {
    console.error('上传文档失败:', error)
    ElMessage.error('上传文档失败: ' + error.message)
  }
}

// 下载文档
async function downloadDocument(doc) {
  try {
    if (doc.fileType === 'link') {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(doc.url)
      ElMessage.success('链接已复制到剪贴板')
    } else {
      // 下载文件
      const link = document.createElement('a')
      link.href = doc.url
      link.download = doc.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage.success('开始下载文档')
    }
  } catch (error) {
    console.error('下载文档失败:', error)
    ElMessage.error('下载文档失败')
  }
}

// 复制链接
async function copyLink(doc) {
  try {
    await navigator.clipboard.writeText(doc.url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制链接失败:', error)
    ElMessage.error('复制链接失败')
  }
}

// 删除文档
async function deleteDocument(doc) {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${doc.name}"吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const query = new AV.Query('Document')
    query.equalTo('objectId', doc.id)
    const result = await query.first()
    
    if (result) {
      await result.destroy()
      ElMessage.success('文档删除成功')
      await fetchDocuments()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      ElMessage.error('删除文档失败')
    }
  }
}

// 预览文档
function handlePreviewDocument(doc) {
  previewDocument.value = doc
  showPreviewDialog.value = true
}

// 打开链接
function openLink(url) {
  window.open(url, '_blank')
}

// 移动端检测
const isMobile = ref(window.innerWidth <= 700)

// 生命周期
onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.document-category-container {
  padding: 20px;
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-content {
  flex: 1;
}

.breadcrumb {
  margin-bottom: 8px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1677ff;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.filter-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.main-content {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-card {
  padding: 24px;
}

/* 网格视图 */
.document-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.document-card {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.document-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.document-icon {
  text-align: center;
  margin-bottom: 16px;
}

.document-icon .el-icon {
  font-size: 48px;
  color: #409eff;
}

.document-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.document-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.document-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px 0;
  line-height: 1.5;
  flex: 1;
}

.document-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.document-category {
  font-size: 12px;
  color: #409eff;
  background: #e6f7ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.document-size {
  font-size: 12px;
  color: #999;
}

.document-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 列表视图 */
.document-list {
  width: 100%;
}

.document-name-cell {
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 预览对话框 */
.preview-content {
  max-height: 70vh;
  overflow-y: auto;
}

.preview-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-header h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.preview-header p {
  margin: 0;
  color: #666;
}

.preview-body {
  padding: 20px 0;
}

.link-preview, .file-preview {
  text-align: center;
  padding: 40px 20px;
}

.image-preview {
  text-align: center;
}

.selected-file {
  margin-top: 8px;
  padding: 8px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 4px;
  color: #0369a1;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-category-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .filter-left {
    width: 100%;
  }
  
  .document-grid {
    grid-template-columns: 1fr;
  }
  
  .document-actions {
    justify-content: center;
  }
}
</style> 